package replic.driver;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import replic.commons.jdbc.Message;

/**
 * 
 * @author Leonardo Oliveira Moreira
 * 
 */
public class RepliCConnection implements Connection {

    private String host;
    private int port;
    private Socket s;
    private ObjectOutputStream outputStream;
    private ObjectInputStream inputStream;
    private boolean autoCommit, closed, readOnly;
    private Properties props;
    
    private RepliCDatabaseMetaData databaseMetaData;
    
    private long id;
    
    public long getConnectionID() {
        return id;
    }

    public RepliCConnection(String host, int port, Properties props) throws SQLException {
        this.id = System.currentTimeMillis();
        this.host = host;
        this.port = port;
        this.props = props;
        try {
            s = new Socket(host, port);
            s.setTcpNoDelay(true);
            outputStream = new ObjectOutputStream(s.getOutputStream());
            inputStream = new ObjectInputStream(s.getInputStream());
        } catch (IOException e) {
            throw new SQLException("unable to connect to database: " + e.getMessage());
        }
        synchronized (this) {
            replic.commons.jdbc.Message message = new replic.commons.jdbc.Message();
            message.setDatabase(props.getProperty("databaseName"));
            message.setSqlType(replic.commons.jdbc.Message.SQL_CONNECTION_CREATE);
            message = executeMessage(message);
            if (message.getState() == Message.STATE_FAILURE) {
                throw new SQLException("Failed to open connection");
            }
        }
        this.autoCommit = true;
        this.readOnly = false;
        this.databaseMetaData = new RepliCDatabaseMetaData();
    }

    /**
     * 
     * @param message
     * @return
     * @throws SQLException 
     */
    public synchronized replic.commons.jdbc.Message executeMessage(replic.commons.jdbc.Message message) throws SQLException {
        try {
            outputStream.writeObject(message);
            outputStream.flush();
            try {
                Object obj = inputStream.readObject();
                message = (replic.commons.jdbc.Message) obj;
            } catch (ClassNotFoundException e) {
                throw new SQLException(e.toString());
            }
        } catch (IOException e) {
            throw new SQLException(e.toString());
        } finally {
            
        }
        if (message.getState() != Message.STATE_SUCCESS) {
            System.out.println(message.toString());
        }
        return message;
    }

    protected void finalize() throws Throwable {
        if (!closed) {
            close();
        }
    }

    @Override
    public synchronized Statement createStatement() throws SQLException {
        RepliCStatement statement = new RepliCStatement(this);
        Message message = new Message();
        message.setSqlType(replic.commons.jdbc.Message.SQL_STATEMENT_CREATE);
        message.setStatementID(statement.getStatementID());
        message.setDatabase(getDatabaseName());
        message = executeMessage(message);
        if (message.getState() == Message.STATE_FAILURE) {
            throw new SQLException("Failed to close statement");
        }
        return statement;
    }

    @Override
    public synchronized PreparedStatement prepareStatement(String sql) throws SQLException {
        RepliCPreparedStatement preparedStatement = new RepliCPreparedStatement(this, sql);
        Message message = new Message();
        message.setSqlType(replic.commons.jdbc.Message.SQL_STATEMENT_CREATE);
        message.setStatementID(preparedStatement.getStatementID());
        message.setDatabase(getDatabaseName());
        message = executeMessage(message);
        if (message.getState() == Message.STATE_FAILURE) {
            throw new SQLException("Failed to close statement");
        }
        return preparedStatement;
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return sql;
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        if (autoCommit == this.autoCommit) {
            return;
        }
        this.autoCommit = autoCommit;
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return this.autoCommit;
    }

    @Override
    public synchronized void commit() throws SQLException {
        try {
            replic.commons.jdbc.Message message = new replic.commons.jdbc.Message();
            message.setDatabase(props.getProperty("databaseName"));
            message.setSqlType(replic.commons.jdbc.Message.SQL_COMMIT);
            message = executeMessage(message);
            if (message.getState() == Message.STATE_FAILURE) {
                throw new SQLException("Failed to commit connection");
            }
        } finally {

        }
    }

    @Override
    public synchronized void rollback() throws SQLException {
        try {
            replic.commons.jdbc.Message message = new replic.commons.jdbc.Message();
            message.setDatabase(props.getProperty("databaseName"));
            message.setSqlType(replic.commons.jdbc.Message.SQL_ROLLBACK);
            message = executeMessage(message);
            if (message.getState() == Message.STATE_FAILURE) {
                throw new SQLException("Failed to commit connection");
            }
        } finally {

        }
    }

    @Override
    public synchronized void close() throws SQLException {
        try {
            replic.commons.jdbc.Message message = new replic.commons.jdbc.Message();
            message.setDatabase(props.getProperty("databaseName"));
            message.setSqlType(replic.commons.jdbc.Message.SQL_CONNECTION_CLOSE);
            message = executeMessage(message);
            if (message.getState() == Message.STATE_FAILURE) {
                throw new SQLException("Failed to close connection");
            }
        } finally {
            closed = true;
            try {
                s.close();
            } catch (IOException e) {
                throw new SQLException("close failed: " + e.getMessage());
            }
        }
    }

    @Override
    public boolean isClosed() throws SQLException {
        return closed;
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return databaseMetaData;
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        if (readOnly == this.readOnly) {
            return;
        }
        this.readOnly = readOnly;
    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return this.readOnly;
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String getCatalog() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {
        
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return Connection.TRANSACTION_SERIALIZABLE;
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void clearWarnings() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setHoldability(int holdability) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public int getHoldability() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Clob createClob() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Blob createBlob() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NClob createNClob() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return !this.closed;
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public String getDatabaseName() {
        return props.getProperty("databaseName");
    }
}
